package com.yellowcong.test;

import java.lang.reflect.Method;

import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

/**
*
*作者:yellowcong
*日期:2017/08/31
*時間:9:57:55
*描述:
*/
public class Demo5 {

	public static void main(String[] args) {
		
		BookDemoProxy proxy = new BookDemoProxy(new BookServieDemo());
		
		BookServieDemo service = (BookServieDemo) proxy.getProxy();
		
		String str = service.add("Think in AOP");
		System.out.println(str);
	}
}
class BookDemoProxy implements MethodInterceptor{
	private Object target ;

	/**
	 * 代理对象实例化的时候，就绑定代理
	 * @param target
	 */
	public BookDemoProxy(Object target  ) {
		this.target = target ;
	}
	
	/**
	 * 获取代理对象
	 * @return
	 */
	public Object getProxy() {
		return Enhancer.create(this.target.getClass(), this);
	}
	
	@Override
	public Object intercept(Object obj, Method method, Object[] args, MethodProxy methodProxy) throws Throwable {
		Object ret = null;
		
		System.out.println("proxy before");
		ret = method.invoke(this.target, args);
		System.out.println("proxy end");
		
		return ret;
	}
	
}
class BookServieDemo{

	public String add(String name) {
		System.out.println("Book Add Method");
		return "添加书籍"+name;
	}
}